package com.rajaev.dtu.tractor.domain.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.rajaev.dtu.tractor.app.service.CustomerService;
import com.rajaev.dtu.tractor.infrastructure.base.enums.CustomerType;
import com.rajaev.dtu.tractor.domain.vo.CustomerVo;
import com.rajaev.dtu.tractor.domain.entity.CustomerPo;
import com.rajaev.dtu.tractor.domain.repository.mysql.CustomerDao;
import com.rajaev.dtu.tractor.domain.repository.mysql.UserCustomerDao;
import com.rajaev.dtu.tractor.infrastructure.base.errors.BusinessException;
import com.rajaev.dtu.tractor.infrastructure.base.errors.ErrorCodes;
import com.rajaev.dtu.tractor.interfaces.dto.CustomerWithProjectTeamVo;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Service
public class CustomerServiceDomain implements CustomerService {

    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    @Autowired
    CustomerDao customerDao;

    @Autowired
    UserCustomerDao userCustomerDao;

    @Autowired
    Mapper dozerMapper;

    @Override
    public void save(CustomerVo customerVo, Integer userId) throws BusinessException {
        if (null != customerDao.selectByCustomerName(customerVo.getCustomerName())) {
            //客户名称重复
            throw new BusinessException(ErrorCodes.ERR_CUSTOMER_HAS_EXIST);
        }

        assertLicenceIsExist(customerVo.getId(),customerVo.getCustomerType(),customerVo.getBusinessLicense());

        CustomerPo customerPo = dozerMapper.map(customerVo, CustomerPo.class);

        readWriteLock.writeLock().lock();
        try{
            if (1 != customerDao.saveCustomer(customerPo)) {
                throw new BusinessException(ErrorCodes.ERR_UPDATE_0_ROWS);
            }

            //添加客户成功后，将客户关联到当前的用户下
            userCustomerDao.insert(new ArrayList(){{add(customerPo.getId());}},userId);

        }finally {
            readWriteLock.writeLock().unlock();
        }

    }

    @Override
    public void updateCustomer(CustomerVo customerVo) throws BusinessException {
        if (!customerVo.getCustomerName().equalsIgnoreCase(customerDao.selectByCustomerId(customerVo.getId()).getCustomerName())) {

            if (null != customerDao.selectByCustomerName(customerVo.getCustomerName())) {
                //客户名称重复
                throw new BusinessException(ErrorCodes.ERR_CUSTOMER_HAS_EXIST);
            }
        }

        assertLicenceIsExist(customerVo.getId(),customerVo.getCustomerType(),customerVo.getBusinessLicense());

        CustomerPo customerPo = dozerMapper.map(customerVo, CustomerPo.class);
        readWriteLock.writeLock().lock();
        try{
            if (1 != customerDao.updateCustomer(customerPo)) {
                throw new BusinessException(ErrorCodes.ERR_UPDATE_0_ROWS);
            }
        }finally {
            readWriteLock.writeLock().unlock();
        }

    }

    /**
     * 校验刻的执照号或者身份证号是否已存在
     * @param customerId
     * @param customerType
     * @param licence
     * @throws BusinessException
     */
    private void assertLicenceIsExist(Integer customerId, CustomerType customerType, String licence) throws BusinessException {
        readWriteLock.readLock().lock();
        try{
            if (null != customerDao.selectCustomerByLicenceExceptId(licence, customerId)) {
                if (customerType.equals(CustomerType.organization)) {
                    //企业客户
                    throw new BusinessException(ErrorCodes.ERR_CUSTOMER_LICENCE_HAS_EXIST);
                } else {
                    //个人客户
                    throw new BusinessException(ErrorCodes.ERR_CUSTOMER_SFZ_HAS_EXIST);
                }
            }
        }finally {
            readWriteLock.readLock().unlock();
        }

    }

    @Override
    public void deleteCustomer(Integer customerId) throws BusinessException {

        readWriteLock.writeLock().lock();
        try{
            if (1 != customerDao.deleteCustomer(customerId)) {
                throw new BusinessException(ErrorCodes.ERR_UPDATE_0_ROWS);
            }
        }finally {
            readWriteLock.writeLock().unlock();
        }

    }


    @Override
    public PageInfo<CustomerVo> pageQueryCustomer(Integer pageSize, Integer pageNo) {
        return PageHelper.startPage(pageNo, pageSize).doSelectPageInfo(() -> customerDao.selectCustomers());
    }

    /**
     * 根据用户id，查询当前用户管理的客户信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<CustomerWithProjectTeamVo> selectCustomerVosByUserId(Integer userId) {
        return customerDao.selectCustomerVoByUserId(userId);
    }


    @Override
    public List<CustomerVo> selectCustomerVosByName(String customerName) {
        return customerDao.selectCustomerByName(customerName);
    }



}
